import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'

Vue.use(VueRouter)

// 解决编程式导航点击同一个按钮时会报错(vue-router 3.0.0 后面都会有这个官方bug)
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch(err => {})
};

const routes = [{
        path: '/',
        redirect: '/home',
    },
    {
        path: '/home',
        name: 'Home',
        component: () =>
            import ( /* webpackChunkName: "about" */ '../views/Home/Home.vue')
    },
    {
        path: '/goods',
        name: 'Goods',
        component: () =>
            import ( /* webpackChunkName: "goods" */ '../views/Goods/Goods.vue')
    },
    {
        path: '/order',
        name: 'Order',
        component: () =>
            import ( /* webpackChunkName: "order" */ '../views/Order/Order.vue')
    },
    {
        path: '/free',
        name: 'Free',
        component: () =>
            import ( /* webpackChunkName: "free" */ '../views/Free/Free.vue')
    },
    {
        path: '/user',
        name: 'User',
        component: () =>
            import ( /* webpackChunkName: "user" */ '../views/User/User.vue'),
        redirect: '/user/cart',
        children:[
            {
                //path:'cart'  //这样写也可以
                path:'/user/cart',
                component: () => import('../components/user/Cart.vue')
            }
        ]
    },
    {
        path: '/detail',
        name: 'Detail',
        component: () =>
            import ( /* webpackChunkName: "detail" */ '../views/Detail/Detail.vue')
    },
    {
        path:'*',  //只要不是前面的路径，都给一个错误页面。防止用户乱输地址
        name:'Error',
        component: () =>
            import ( /* webpackChunkName: "error" */ '../views/Error/Error.vue')
    }

]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

/*
    在进入某个组件之前(路径切换)，我们可能需要做一些工作,
    我们会把这些代码都放进路由守卫(守卫导航，路由拦截),在router配置文件的配置我们叫全局路由守卫
    理解为：在进入这个路由 之前/之后，拦截下来做一些工作

    现需求：进入个人中心 /user 前，需要判断是否已经登录
*/

// 全局前置导航守卫

router.beforeEach((to,from,next)=>{
    // to和from都是对象，明确来说就是平时我们在组件中写的 $route 对象
    // to表示要去的路由对象, from表示从哪个路由对象来
    // console.log(to,from)

    // 如果去个人中心需要判断是否已经登录
    /*
    if(to.path == '/user' || to.path == '/order'){
        let token = localStorage.getItem('x-auth-token')
        if(token){
            //有登录就放行
            next()  
        }else{
            // 没登陆就提示
            store._actions['toastStatus/asyncChangeIsShowToast'][0]({
                msg: '您还没登录',
                type: 'danger'
            })
        }

        return   //必须return ，不然代码会往下走
    }  */

    next() // next是一个方法，表示放行通过。如果不调用next，本次跳转就不会被执行
})


export default router